/**
 * Created by yangfan on 2016/10/21.
 */
define(["require",'config/appregister',"i18n","config/uploadFile","business/services/httpServices","business/library/services/httpServices","business/services/constant","business/services/utils",
    "business/home/directives/editorDirective","business/services/fileuploader","business/videoupload/directive/videoupload","upfull"
],function(require,app,i18n,uploadFile,httpService,libHttpServices,constant,unitil){
    app.controller('libraryUploadCtrl',function($scope,$state){
    	//标签
    	$scope.tags2 = [//ngInputTab自己写方法

        ];
        $scope.controlLength = function(str){
            var l = str.length;
            var blen = 0;
            for(var i=0; i<l; i++) {
                if (str.charCodeAt(i) > 255) {
                    blen ++;
                }
                blen ++;
            }
            if(blen == 32){
                var maxLength = $scope.tagsWork.length;
            }
            if(blen > 32){
                $scope.tagsWork.length = maxLength;
            }
        }
        $scope.saveTagsname=function(a){
            if(a == ''){
                return;
            }
        	if($scope.tags2.length == 6){
        		alert('最多只能添加六个关键词哦，亲');
        		return;
        	}
            if($scope.tags2.indexOf(a) != -1){
                alert("关键词不能相同哦")
            }else{
                $scope.tags2.push(a);
                $scope.tagsWork = '';
            }
        }
        $scope.deleteInput=function($index){
            $scope.tags2.splice($index,1);
        }
    	
    	
        $scope.isDetailPage = false;
        $scope.isMainpage = true;
        $scope.showFillInfo = true;
        $scope.i18n = i18n;
        $scope.mainData = {
            logoSrc:"them/images/gcj_big_logo.png"
        };
        $scope.showTemplate = {
            isSelectFile:false,
            isUploadFile:true,
            showFillLeftL:false
        };
        $scope.fillInfo = "您已成功上传1份文件 ， 失败0份";
        $scope.successNoticeInfo = "您已成功上传1个文件，审核通过后，将获得 5 积分";
        $scope.uploadFileName = "";
        $scope.uploadNoticeInfo = "";

        //多文件上传时用于判断文件类型
        $scope.currentFileType = "";

        //文件上传参数
        $scope.uploadInfo  = {
            typeId:"",
            tcId:"",
            scId:"",
            dcId:"",
            name:"",
            size:"",
            tagsId:"",
            price:10,
            introduction:"",
            labels:"",
            labelIds:"",
            author:"",
            resource:"",
            reference:"",
            status:0,
            source:''
        };
        //隐藏二级目录
        $scope.isShowSec = false;
        //获取文件格式
        function getFileType(){
            var reqFile = {
                type: "GET"
            };
            httpService.getFileType(reqFile).success(function (response) {
                $scope.fileType = response.data;
                console.log(response.data)
            });
        }
        getFileType();
        //单文件时 上传文件
        function uploadInfo (){
            //todo 先校验必选项是否全部输入
            // 判断文件类型
            var file = $scope.upload.file;
            if(!file.name){
                return
            }
            var fileName = file.name.toLowerCase();
            $scope.uploadFileName = fileName;
            /* var type = fileName.substr(fileName.lastIndexOf(".")+1);*/
            //var type = unitil.getFileType(file.ext);
            var type = file.ext;
            if(type == "docx"){
                type = "doc";
            }
            var fileTypeId;
            for(var i = 0;i < $scope.fileType.length;i++){
                if($scope.fileType[i].typeName == type){
                    fileTypeId = $scope.fileType[i].typeId;
                }
            }

            var size = file.size;
            if(!$scope.uploadInfo.scId){
                return;
            }
            if($scope.tags2 == []){
                return;
            }
            //判断用户是否已经输入 若非 则不执行添加文件请求
            if(!$scope.uploadInfo.tcId||!$scope.uploadInfo.scId||!$scope.uploadInfo.name||!$scope.uploadInfo.price||!$scope.uploadInfo.price||!$scope.resource.title || !$scope.resource.date ||!$scope.resource.startPage ||!$scope.resource.endPage){
                return;
            }
            if(!$scope.uploadInfo.reference){
            	$scope.uploadInfo.reference = "";
            }
            var requestion = {
                type:"POST",
                uri:"add",
                data:{
                    labels: $scope.tags2 ==''?$scope.tags2:$scope.tags2.join(',')
                }
            };

            var req = {
                type:"POST",
                uri:"add",
                data:{
                    typeId:fileTypeId,
                    tcId:$scope.uploadInfo.tcId,
                    scId:$scope.uploadInfo.scId,
                    dcId:$scope.uploadInfo.dcId,
                    name:$scope.uploadInfo.name,
                    size:size,
                    price:$scope.uploadInfo.price,
                    path:$scope.upload.path,
                    introduction:$scope.uploadInfo.introduction,
                    labelIds:'',
                    author:$scope.uploadInfo.author,
                    resource:$scope.uploadInfo.resource,
                    source:getSource($scope.resource),
                    reference:$scope.uploadInfo.reference.split('##').join('ㅆ'),
                    status:$scope.uploadInfo.status
                }
            } ;
            if($scope.tags2 == [] || ""){
                return;
            }
                libHttpServices.tagServices(requestion).success(function(response){
                    $scope.uploadInfo.labelIds = response.data.join(",");
                    req.data.labelIds =  $scope.uploadInfo.labelIds;
                    addFileByPost(req)
                }).error(function(){
                })
        }
        //传 resource 对象 返回 展示样式
      function getSource (obj){
          var str = obj.title + ',' +obj.date + ';';
          if($scope.uploadInfo.status ==1){
             str = str +  obj.startPage + '-' + obj.endPage ;
          }
          return str
      }

        // 论文来源
        $scope.resource = {
            title:'',
            date:'',
            startPage:'',
            endPage:''
        }


        //getTop   // 论文来源
        $scope.resource = {
            title:'',
            date:'',
            startPage:'',
            endPage:''
        }
        function getTopCategory (){
            var req = {
                type:"GET",
                uri:"getTopCategory"
            };
            libHttpServices.getTopCategory(req).success(function(response){
                if(!response.data)return ;
                $scope.$apply(function(){
                    $scope.engClassify = response.data;
                });
            }).error(function(data){
                console.log("请求错误");
            });
        };

        //getSecCategory
        function getSecCategory (tcId){
            var req = {
                type:"GET",
                uri:"getSecondaryCategory",
                data:{
                    tcId :tcId
                }
            };
            libHttpServices.getSecondaryCategory(req).success(function(response){
                if(!response.data) return ;
                $scope.$apply(function(){
                    $scope.isShowSec = true;
                    $scope.secCate = response.data;
                });
            }).error(function(

            ){})

        };
        function getDetailCategory(){
            var req = {
                type:"GET",
                uri:"getDetailCategory",
                data:{
                    scId :$scope.uploadInfo.scId
                }
            };
            libHttpServices.getDetailCategory(req).success(function(response){
                if(!response.data) return ;
                $scope.$apply(function(){
                    $scope.curDetail = response.data;
                });
            }).error(function(

            ){})
        }


        //点击确认 上传文件信息
        function addFileByPost(req){
            libHttpServices.addFile(req).success(function(response){

                $scope.$apply(function(){
                    $scope.coinValue = 0;
                    if(response.data){
                        $scope.coinValue = response.data.coinValue
                    }
                    $scope.showFillInfo = false;
                });
            }).error(function(){
                $scope.uploadNoticeInfo = "文件上传失败";
            })
        }

        //初始化一级目录分类
        getTopCategory();

        var backgroundObj = {
            background:"#00A4FF",
            color:"#fff"
        };

        // TopCategory options  change事件
        $scope.changeTcOptions = function(item,index){
            $scope.isCheckForTc = [];
            $scope.isCheckForSc = [];
            $scope.isCheckForDc = [];
            $scope.isCheckForTc[index] = backgroundObj ;

            //topOptions 改变 隐藏二三级分类 select 选择框
            if( $scope.isShowNationDec == true){
                $scope.isShowNationDec = false;
            };
            if( $scope.isShowInterDec == true){
                $scope.isShowInterDec = false;
            };
            if(!item){
                if( $scope.isShowSec == true){
                    $scope.isShowSec = false;
                };
                return
            };
            $scope.uploadInfo.tcId = item.tcId;
            getSecCategory(item.tcId)  ;
        };

        // SecCategory options  change事件
        $scope.changeScOptions = function(item,index){

            if(!item)return;
            $scope.uploadInfo.dcId = "";
            $scope.uploadInfo.scId = item.scId;
            $scope.isCheckForSc = [];
            $scope.isCheckForDc = [];
            $scope.isCheckForSc[index] = backgroundObj ;
            $scope.isShowNationDec = true;
            getDetailCategory();
        };
        $scope.changeDcOptions = function(item ,index){

            $scope.isCheckForDc = [];
            $scope.isCheckForDc[index] = backgroundObj ;
            if(!item) return ;
            $scope.uploadInfo.dcId = item.dcId;
        };

        //select 复选框设置
        var expanded = false;
        $scope.showCheckboxes = function(){
            var checkboxes = document.getElementById("checkboxes");
            if (!expanded) {
                checkboxes.style.display = "block";
                expanded = true;
            } else {
                checkboxes.style.display = "none";
                expanded = false;
            }
        };

        // 获取国际情形下 三级分类复选 选中的id数组
        $scope.interDc = [];
        $scope.changeCheckbox = function(event,item){
            if(!item){
                return ;
            }

            //如果选中 则插入
            if(event.target.checked){
                if($scope.interDc.indexOf(item.dcId)==-1){
                    $scope.interDc.push(item.dcId);
                }
            }

            // 如果取消选中 则从数组中移除
            if(!event.target.checked){
                var index = $scope.interDc.indexOf(item.dcId);
                if(index!=-1){
                    $scope.interDc.splice(index, 1);
                }
            }
            $scope.uploadInfo.dcIds =  $scope.interDc;
        };

        $scope.addFile = function(){
            uploadInfo();
        };
        $scope.editFileInfo = function(){
            var fileObj = document.getElementById("file").files[0];
            var fileName = fileObj.name.toLowerCase();
            $scope.uploadNoticeInfo = "文件填写中";
            $scope.uploadFileName = fileName;
            $scope.showTemplate.showFillLeftL = !$scope.showTemplate.showFillLeftL;
            if($scope.editSrc == $scope.src.V){
                $scope.editSrc = $scope.src.A;
            }else{
                $scope.editSrc = $scope.src.V;
            }
        };
        $scope.src = {
            V:"them/images/V_logo.png",
            A:"them/images/A_logo.png"
        };
        $scope.editSrc = $scope.src.V;
        $scope.upload = {
            url:'http://101.37.82.219:8087',
            api:constant.config.CONSTANT_UPLOADER,
            path:"",
            file:"",

            onchange:function(){
            }
        };
        $scope.$on("uploadSuccess",function(data){
            $scope.$apply(function(){
                $scope.showTemplate.isSelectFile = true;
                $scope.showTemplate.isUploadFile = false;
            })
        })
        $scope.goTo = function(state){
            if(state == 'eng.libraryUpload'){
                $state.transitionTo(state, {}, {
                    reload: true, inherit: false, notify: true
                });
            }else{
                $state.go(state);
            }
        };





    })
});

